<?php

declare(strict_types=1);
/**
 * sql执行日志
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2022/3/26.
 */

namespace App\Service;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class LogSqlService
{
    public static $sqlResults = [];

    public static function listen(): void
    {
        if (!Config::get('logging.custom.sql.enable')) {
            return;
        }

        DB::listen(function ($query): void {
            $slow = (int) Config::get('logging.custom.sql.slow');
            if ($slow && $slow > $query->time) {
                return;
            }
            $location = static::getSqlFiles();
            static::$sqlResults[] = [
                'Sql' => static::getSql($query),
                'Time' => $query->time,
                'File' => $location['file'],
                'Line' => $location['line'],
            ];
        });
    }

    public static function getSqlFiles(): array
    {
        $location = ['file' => '', 'line' => ''];
        if (Config::get('logging.custom.sql.locality')) {
            $location = collect(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))->filter(function ($trace) {
                if (isset($trace['file'])) {
                    return !str_contains($trace['file'], 'vendor/');
                }

                return false;
            })->first();
        }

        return $location;
    }

    public static function getSql($query): string
    {
        $binding_sql = $query->sql;
        if (Config::get('logging.custom.sql.format')) {
            $sql = str_replace('%', "'%%'", $query->sql);
            $sql = str_replace('?', '"'.'%s'.'"', $sql);
            $binding_sql = vsprintf($sql, $query->bindings);
        }

        return $binding_sql;
    }

    public static function getSqlResults(): array
    {
        return static::$sqlResults;
    }
}
